//
//  CarCartoryTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/4.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "CarCartoryTableViewController.h"
#import "CarprogChildmode.h"
#import "CarprogMode.h"
#import "CarProgResdmode.h"
#import <UIImageView+WebCache.h>
#import "CaChidTableViewController.h"
#import <MJExtension.h>
#import "NumModel.h"
#import "NoChoiceModel.h"

@interface CarCartoryTableViewController ()
@property (nonatomic,weak) UIView *header;
@property (nonatomic,weak) UIButton *cancelbtn;
@property (nonatomic,weak) UIImageView *icon;
@property (nonatomic,weak) UILabel *titlelable;
@property (nonatomic,strong) NSMutableArray *sectionArray;
@property (nonatomic,assign) NSInteger num;
@end

@implementation CarCartoryTableViewController
+(instancetype)viewcontroller{
   CarCartoryTableViewController *cavc= [XHMianStory instantiateViewControllerWithIdentifier:@"cavc"];
    return cavc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     [self setExtraCellLineHidden:self.tableView];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
  
}
-(void)setMode:(CarbrandModel *)mode{
    _mode=mode;
    if (self.isFromfind) {
        self.navigationItem.title=mode.brand_name;
    }
    [self loadmode];
}

-(void)loadmode{
    if (self.isFromfind) {
        
    }else{
        [self.icon sd_setImageWithURL:[NSURL URLWithString:[NSString getImageURLstr:_mode.brand_logo]] placeholderImage:[UIImage imageNamed:@"placehoder"]];
        self.titlelable.text=_mode.brand_name;
    }
   
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    if (self.type) {
        params[@"brand_id"]=_mode.brand_id;
        params[@"action"]=@"b_cat";
        params[@"type"]=self.type;
    }else{
        params[@"action"]=@"prog";
        params[@"parent"]=_mode.brand_id;
    }
    
    [PostUitls Post:maketypeurl parameters:params success:^(id response) {
        
        NSDictionary *dict=response;
        CarProgResdmode *resdmode=[CarProgResdmode progWithDict:dict];
        [self.sectionArray removeAllObjects];
        if (!self.isFromfind) {
            NoChoiceModel *mode=[[NoChoiceModel alloc]init];
            mode.cat_name=@"#";
            CarprogChildmode *chlidmode=[[CarprogChildmode alloc]init];
            chlidmode.cat_name=@"全部车源";
            mode.children=@[chlidmode];
            [self.sectionArray addObject:mode];
        }
        [self.sectionArray addObjectsFromArray:resdmode.data];
        [self.tableView reloadData];
        if (!self.DonotNotice) {
             [self nocticenum];
        }
       
        if (!self.isFromfind) {
            
            if (self.indexpath) {
            [self.tableView selectRowAtIndexPath:self.indexpath animated:YES scrollPosition:UITableViewScrollPositionNone];
            }else{
                NSIndexPath *first=[NSIndexPath indexPathForRow:0 inSection:0];
                [self.tableView selectRowAtIndexPath:first animated:YES scrollPosition:UITableViewScrollPositionNone];
            }
           

        }
        
        NSLog(@"%@",response);
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
   
}
    

-(void)nocticenum{
    NSMutableDictionary *params2=[NSMutableDictionary dictionary];
    params2[@"action"]=@"count";
    NSMutableDictionary *conndict=[NSMutableDictionary dictionary];
    conndict[@"brand_name"]=_mode.brand_name;
    
    params2[@"cond"]=[NSString DataTOjsonString:conndict];
    [PostUitls Post:sscarurl parameters:params2 success:^(id response) {
        NSDictionary *dict=response;
        NumModel *mode=[NumModel objectWithKeyValues:dict];
        if ([mode.state integerValue]==400) {
            
            NSMutableDictionary *userinfo=[NSMutableDictionary dictionary];
            userinfo[@"num"]=mode.num;
            self.num=[mode.num integerValue];
            NSNotification *notice=[[NSNotification alloc]initWithName:NoticeCount object:nil userInfo:userinfo];
            [[NSNotificationCenter defaultCenter] postNotification:notice];
        }
    } failure:^(NSError *error) {
        
    }];

}

- (void)setExtraCellLineHidden: (UITableView *)tableView{
    
    UIView *view =[ [UIView alloc]init];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
    [tableView setTableHeaderView:view];
    
}

-(NSMutableArray *)sectionArray{
    if (_sectionArray==nil) {
        _sectionArray=[NSMutableArray array];
    }
    return _sectionArray;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    }
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
-(void)setupHeader:(CGFloat)width{
    UIView *header=[[UIView alloc] initWithFrame:CGRectMake(0, 0, width, 44)];
    UIImageView *icon=[[UIImageView alloc]initWithFrame:CGRectMake(8, 4, 36, 36)];
    icon.image=[UIImage imageNamed:@"list_icon"];
    [header addSubview:icon];
    _icon=icon;
    UILabel *titlelable=[[UILabel alloc]initWithFrame:CGRectMake(52, 4, width-46, 36)];
   
    titlelable.text=@"品牌";
    titlelable.font=[UIFont systemFontOfSize:14];
    [header addSubview:titlelable];
    self.titlelable=titlelable;
    UIButton *cancelbtn=[[UIButton alloc]initWithFrame:CGRectMake(width-38, 12, 20, 20)];
    [cancelbtn setImage:[UIImage imageNamed:@"ico_bright.png"] forState:UIControlStateNormal];
    [header addSubview:cancelbtn];
    self.cancelbtn=cancelbtn;
    self.header=header;
    [self.cancelbtn addTarget:self action:@selector(cancelclick) forControlEvents:UIControlEventTouchUpInside];
     self.tableView.tableHeaderView=header;
}
-(void)cancelclick{
    NSLog(@"CANCEL");
    if ([_delegate respondsToSelector:@selector(CarCartorycancelclick)]) {
        [_delegate CarCartorycancelclick];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return self.sectionArray.count;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
        CarprogMode *mode=self.sectionArray[section];
        return mode.cat_name;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
  
        CarprogMode *mode=self.sectionArray[section];
        return mode.children.count;
    
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = UIColorWithRGB(242, 242, 242);
    
    // Text Color
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.textLabel setTextColor:UIColorWithRGB(138, 138, 138)];
    [header.textLabel setFont:[UIFont systemFontOfSize:14]];
    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // header.contentView.backgroundColor = [UIColor blackColor];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chexi"];
   
        CarprogMode *mode=self.sectionArray[indexPath.section];
        CarprogChildmode *childmode=mode.children[indexPath.row];
        cell.textLabel.text=childmode.cat_name;
   
//        cell.textLabel.highlightedTextColor=textnormalGary;

        cell.textLabel.highlightedTextColor=tintblue;
    
    // Configure the cell...
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CarprogMode *mode=self.sectionArray[indexPath.section];
    CarprogChildmode *childmode=mode.children[indexPath.row];
 
    if ([mode isKindOfClass:[NoChoiceModel class]]) {
        return;
    }
   
    if (self.num!=0) {
        
        if ([_delegate respondsToSelector:@selector(carcartoryClick:withBrandmode:withIndexPath:)]) {
            [_delegate carcartoryClick: childmode withBrandmode:self.mode withIndexPath:indexPath];
        }
    }
    
    if (self.isFromfind) {
        CaChidTableViewController *cavc=[CaChidTableViewController viewcontroller];
        cavc.type=self.type;
        cavc.car=self.mode;
        cavc.mode=childmode;
        cavc.carindexpath=indexPath;
        [self.navigationController pushViewController:cavc animated:YES];
    }
    
    
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
